﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using TfsComLib.TfsBranchLib2;
using WpfAdvControls;
using WpfAdvControls.StatusPanel;

namespace TfsBranchLib2.View
{
    /// <summary>
    ///     Interaction logic for BranchComboBox.xaml
    /// </summary>
    public partial class BranchComboBox : UserControl
    {
        public static readonly DependencyProperty SelectedBranchProperty = DependencyProperty.Register(
            "SelectedBranch", typeof (BranchData), typeof (BranchComboBox),
            new FrameworkPropertyMetadata(new BranchData(), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
                OnSelectedBranchChanged));

        // Using a DependencyProperty as the backing store for SourceBranches.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty SourceBranchesProperty =
            DependencyProperty.Register("SourceBranches", typeof (ISourceBranches), typeof (BranchComboBox),
                new FrameworkPropertyMetadata(null));


        public LibCommand BranchSettingsCommand;


        public BranchComboBox()
        {
            InitializeComponent();
            BranchSettingsCommand = new LibCommand(ShowSettings, false);
            BranchSettingsCommand.ApplyToButton(settings);
            branchCombo.DataContext = this;
            branchCombo.SetBinding(Selector.SelectedValueProperty, "SelectedBranch");
            branchesProviderStatus.DataContext = SourceBranches;
            var statusBinding = new Binding();
            statusBinding.Path = new PropertyPath("SourceBranches.IsErrorOrConnectionProblem");
            statusBinding.Converter = new NegativeBoolConverter();
            branchesProviderStatus.SetBinding(StatusBox.StatusProperty, statusBinding);
            branchesProviderStatus.DataContext = this;
            branchesProviderStatus.SetBinding(StatusBox.StatusTextProperty, "SourceBranches.ServiceStatus");
            UpdateBranchList();
        }

        private List<BranchData> branchList { get; set; }


        public ISourceBranches SourceBranches
        {
            get { return (ISourceBranches) GetValue(SourceBranchesProperty); }
            set { SetValue(SourceBranchesProperty, value); }
        }


        public BranchData SelectedBranch
        {
            get { return (BranchData) (GetValue(SelectedBranchProperty)); }
            set { SetValue(SelectedBranchProperty, value); }
        }

        public void ShowSettings()
        {
            var settings = new SourceControlBasePathSettingsWindow(Window.GetWindow(this), SourceBranches);
            settings.ShowDialog();
            UpdateBranchList();
        }

        public void UpdateBranchList()
        {
            var branchData = SelectedBranch;
            if (SourceBranches != null)
            {
                try
                {
                    branchList = SourceBranches.GetBranchList();
                    if (!SourceBranches.IsErrorOrConnectionProblem)
                    {
                        branchList.Sort((BranchData a, BranchData b) => { return string.Compare(a.Name, b.Name); });
                        branchCombo.ItemsSource = branchList;
                        if (branchData != null)
                        {
                            var newSelected = branchList.Find((BranchData bd) =>
                            {
                                if (bd.ServerPath == branchData.ServerPath) return true;
                                return false;
                            });
                            if (newSelected != null)
                            {
                                SelectedBranch = newSelected;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (!SourceBranches.IsErrorOrConnectionProblem)
                    {
                        branchesProviderStatus.Status = false;
                        branchesProviderStatus.StatusText = ex.Message;
                    }
                }
            }
        }

        private static void OnSelectedBranchChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var branchComboBox = (BranchComboBox) d;
            if (e.NewValue == null) return;
            if (branchComboBox.branchCombo.Items.Count == 0)
            {
                branchComboBox.UpdateBranchList();
                return;
            }
            var serverPath = ((BranchData) (e.NewValue)).ServerPath;
            foreach (var item in branchComboBox.branchCombo.Items)
            {
                var branchData = item as BranchData;
                if (branchData != null)
                {
                    if (branchData.ServerPath == serverPath)
                    {
                        branchComboBox.branchCombo.SelectedItem = item;
                        return;
                    }
                }
            }
        }

        private void BranchComboDropDownOpened(object sender, EventArgs e)
        {
            if ((branchCombo.ItemsSource == null) || (branchCombo.Items.Count < 1))
            {
                UpdateBranchList();
            }
        }
    }
}